package boot

import (
	"OrgManager/app/service"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/text/gregex"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func init() {

	s := g.Server()

	// Web Server配置
	s.BindHookHandlerByMap("/admin/*.bu", map[string]ghttp.HandlerFunc{
		ghttp.HOOK_BEFORE_SERVE: func(r *ghttp.Request) {
			if r.Session.Contains(service.SESSION_KEY_MEMBER) {
				orgMember := gconv.Map(r.Session.Get(service.SESSION_KEY_MEMBER))
				glog.Debug("登录信息： %s \r\n", orgMember["name"])
				powerList := fmt.Sprintf("%s", orgMember["power_list"])
				glog.Debug("powerList： %s \r\n", powerList)
				officeList := fmt.Sprintf("%v", orgMember["office_list"])
				glog.Debug("officeList： %v \r\n", officeList)

				url := r.URL.Path
				glog.Debug("URL地址:" + url)
				match, _ := gregex.MatchString("/(\\w+)/(\\w+)[!\\.]", url)
				glog.Debug("方法：%s 表:%s  \r\n", match[1], match[2])

				powers, err := g.DB().Table("sys_power").Where("controller= ? and method = ?", match[2], match[1]).One()
				if err == nil && !strings.Contains(powerList, gconv.String(powers["code"]) ) {
					glog.Info("没有权限： %s \r\n",  powers["code"].Int())

					r.Response.WriteJson(g.Map{
						"code":  -1002,
						"msg":  fmt.Sprintf("对不起，您没有该操作的权限！权限:%d \r\n", powers["code"].Int()),
						"bundle": nil,
					})
					r.ExitAll()
				}
			} else {
				glog.Debug("未登录，请重新登录！")

				r.Response.WriteJson(g.Map{
					"code":  -1001,
					"msg":  "您的登录信息已失效，请重新登录",
					"bundle": nil,
				})
				r.ExitAll()
			}
		},
		//ghttp.HOOK_AFTER_SERVE:   func(r *ghttp.Request) { fmt.Println("222222222") },
		//ghttp.HOOK_BEFORE_OUTPUT: func(r *ghttp.Request) { fmt.Println("333333333") },
		//ghttp.HOOK_AFTER_OUTPUT:  func(r *ghttp.Request) { fmt.Println("444444444") },
	})

}
